"""
Kimi API路由处理器模块
包含所有Kimi API端点的处理函数
"""

import asyncio
import os
import random
import time
import uuid
import json
from typing import Dict, List, Any, Set, Optional
from asyncio import Queue, Future, Lock, Event
import logging

from fastapi import HTTPException, Request, WebSocket, WebSocketDisconnect, Depends
from fastapi.responses import JSONResponse, FileResponse, StreamingResponse
from pydantic import BaseModel
from playwright.async_api import Page as AsyncPage

# --- 配置模块导入 ---
from config import *

# --- models模块导入 ---
from models import ChatCompletionRequest, WebSocketConnectionManager

# --- 依赖项导入 ---
from .dependencies import *

# --- Kimi控制器导入 ---
from browser_utils.kimi_controller import KimiController

async def kimi_chat_completions(
    request: ChatCompletionRequest,
    http_request: Request,
    logger: logging.Logger = Depends(get_logger),
    request_queue: Queue = Depends(get_request_queue),
    server_state: Dict[str, Any] = Depends(get_server_state),
    worker_task = Depends(get_worker_task),
    kimi_controller: Optional[KimiController] = Depends(get_kimi_controller)
):
    """处理Kimi聊天完成请求"""
    req_id = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=7))
    logger.info(f"[{req_id}] 收到 Kimi /v1/chat/completions 请求 (Stream={request.stream})")
    
    # 检查Kimi控制器是否可用
    if kimi_controller is None:
        logger.error(f"[{req_id}] Kimi控制器不可用")
        raise HTTPException(status_code=503, detail=f"[{req_id}] Kimi服务当前不可用，请检查配置。", headers={"Retry-After": "30"})
    
    # 检查服务状态
    launch_mode = os.environ.get('LAUNCH_MODE', 'unknown')
    browser_page_critical = launch_mode != "direct_debug_no_browser"
    
    service_unavailable = server_state["is_initializing"] or \
                          not server_state["is_playwright_ready"] or \
                          (browser_page_critical and (not server_state["is_page_ready"] or not server_state["is_browser_connected"]))
    
    if service_unavailable:
        raise HTTPException(status_code=503, detail=f"[{req_id}] Kimi 服务当前不可用。请稍后重试。", headers={"Retry-After": "30"})
    
    # 处理请求
    try:
        # 检查客户端是否已断开连接
        if await http_request.is_disconnected():
            raise HTTPException(status_code=499, detail=f"[{req_id}] 客户端在处理开始前已断开连接")
        
        # 准备提示
        from api_utils.utils import prepare_combined_prompt
        prepared_prompt, _ = prepare_combined_prompt(request.messages, req_id)
        
        # 提交提示到Kimi
        await kimi_controller.submit_prompt(prepared_prompt, lambda x: False)  # 简化的检查函数
        
        # 等待响应
        response_content = await kimi_controller.get_response(lambda x: False)  # 简化的检查函数
        
        # 构造响应
        if request.stream:
            # 流式响应
            async def generate_stream():
                try:
                    # 分块发送响应
                    chunk_size = 50
                    for i in range(0, len(response_content), chunk_size):
                        chunk = response_content[i:i+chunk_size]
                        yield f"data: {json.dumps({'id': f'chatcmpl-{req_id}', 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': 'kimi', 'choices': [{'index': 0, 'delta': {'content': chunk}, 'finish_reason': None}]})}\n\n"
                        await asyncio.sleep(0.01)  # 模拟流式传输
                    
                    # 发送结束标记
                    yield f"data: {json.dumps({'id': f'chatcmpl-{req_id}', 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': 'kimi', 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n"
                    yield "data: [DONE]\n\n"
                except Exception as e:
                    logger.error(f"[{req_id}] 流式响应生成错误: {e}")
                    yield f"data: {json.dumps({'error': {'message': 'Internal server error'}})}\n\n"
            
            return StreamingResponse(generate_stream(), media_type="text/event-stream")
        else:
            # 非流式响应
            response_data = {
                "id": f"chatcmpl-{req_id}",
                "object": "chat.completion",
                "created": int(time.time()),
                "model": "kimi",
                "choices": [{
                    "index": 0,
                    "message": {
                        "role": "assistant",
                        "content": response_content
                    },
                    "finish_reason": "stop"
                }],
                "usage": {
                    "prompt_tokens": 0,
                    "completion_tokens": len(response_content),
                    "total_tokens": len(response_content)
                }
            }
            return JSONResponse(content=response_data)
            
    except Exception as e:
        logger.error(f"[{req_id}] 处理Kimi请求时出错: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"[{req_id}] 处理Kimi请求时出错: {str(e)}")